package com.cs410.collabwriting.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.cs410.collabwriting.connectors.SessionManager;
import com.cs410.collabwriting.main.Comment;
import com.cs410.collabwriting.main.DatabaseObjects;
import com.cs410.collabwriting.main.Post;
import com.cs410.collabwriting.main.Prompt;
import com.cs410.collabwriting.main.Story;
import com.cs410.collabwriting.main.StoryManager;
import com.cs410.collabwriting.main.Storylist;
import com.cs410.collabwriting.main.TagConstant;
import com.cs410.collabwriting.main.TagManager;
import com.cs410.collabwriting.main.User;
import com.cs410.collabwriting.main.UserManager;

/**
 * Servlet implementation class UpdateHandler
 */
@WebServlet("/update")
public class UpdateHandler extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateHandler() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String page = request.getParameter("page");
		JSONObject json = new JSONObject();

		User user = SessionManager.getUserIDForJSessionIDNoActivity( request.getRequestedSessionId() );
		try {
			if( page != null ) {
				if( page.compareToIgnoreCase("newsfeed") == 0  ) {
					json.put("error", "false");
					json = GetSubscriptionUpdatesAsJSON( json, user == null ? null : user.getUserID() );
				} else if( page.compareToIgnoreCase("user") == 0 ) {
					json.put("error","false");
					String userid = request.getParameter("userid");
					User userlookup = UserManager.getInstance().getUser( userid );
					json = GetUserInfo( json, userlookup );
				} else if ( page.compareToIgnoreCase("browse_stories") == 0 ) {
					json.put("error", "false");
					json = GetStoryListAsJSON( json );
				
				} else if ( page.compareToIgnoreCase("browse_prompts") == 0 ) {
					json.put("error", "false");
					json = GetPromptListAsJSON( json );
					
				} else if ( page.compareToIgnoreCase("top_viewed") == 0) {
					json.put("error", "false");
					json = GetTopViewedListAsJSON( json );
					
				} else if ( page.compareToIgnoreCase("top_voted") == 0) {
					json.put("error", "false");
					json = GetTopVotedListAsJSON( json );
					
				} else if ( page.compareToIgnoreCase("search_stories") == 0 ) {
					String keyword = request.getParameter("keywords");
					String creator = request.getParameter("author");
					String howToSort = request.getParameter("sortBy");
					String tagIndex = request.getParameter("tagIndex");
					
					int numTags = Integer.valueOf(tagIndex);
					String[] tags = new String[numTags];
			
					//Fill up string array with all the selected tags
					for (int i = 0; i < numTags; i++){
						String tagURLName = "tag" + i;
						tags[i] = request.getParameter(tagURLName); 
					}
					
					json.put("error", "false");
					json = GetStorySearchResultsAsJSON( json, keyword, creator, numTags, tags, howToSort );
					
				} 
				
				else if ( page.compareToIgnoreCase("browse_stories_tags") == 0 ) {
					String tagIndex = request.getParameter("tagIndex");
					
					int numTags = Integer.valueOf(tagIndex);
					String[] tags = new String[numTags];
			
					//Fill up string array with all the selected tags
					for (int i = 0; i < numTags; i++){
						String tagURLName = "tag" + i;
						tags[i] = request.getParameter(tagURLName); 
					}
					
					json.put("error", "false");
					json = GetStorySearchResultsAsJSON( json, "", "", numTags, tags, "byview" );
					
				}
				
				else if ( page.compareToIgnoreCase("story_view") == 0 ) {
					String storyid = request.getParameter("storyid");
					if( storyid != null && !storyid.isEmpty() && storyid.compareToIgnoreCase("undefined") != 0  ) {
						json.put("error", "false");
						json = GetStoryInfoForStory( json, storyid, user);
						json.put("userid", ((user != null) ? user.getUserID() : null));
					} else {
						json.put("error","true");
						json.put("reason", "story does not exist!");
					}
				} else if ( page.compareToIgnoreCase("story_comment") == 0 ) {
					String storyid = request.getParameter("storyid");
					if( storyid !=  null && storyid.isEmpty() == false ) {
						Story story = StoryManager.getInstance().getStoryByID( Integer.parseInt(storyid) );
						ArrayList<Comment> comments = story.getAllComments();
						JSONArray commentArray = new JSONArray();
						for( Comment comment : comments ) {
							JSONObject commentJSON = new JSONObject();
							commentJSON.put("comment", comment.getComment());
							commentJSON.put("userid", comment.getUserID() );
							commentJSON.put("storyid", comment.getStoryID() );
							commentJSON.put("timestamp",comment.getTimeStamp() );
							commentJSON.put("commentid", comment.getCommentID());
							commentArray.put( commentJSON );
						}
						json.put("error","false");
						json.put("comments", commentArray );
					} else {
						json.put("error","true");
						json.put("reason","storyid cannot be empty!");
					}
				} else if ( page.compareToIgnoreCase("my_storylist") == 0 && user != null ) {
				    String listid = request.getParameter("listid");
                    if( listid != null && !listid.isEmpty() && listid.compareToIgnoreCase("undefined") != 0  ) {
                        json.put("error", "false");
                        json = GetListForStorylist( json, listid );
                    } else {
                        json.put("error","true");
                        json.put("reason", "list does not exist!");
                    }
				} else if ( page.compareToIgnoreCase("storylist") == 0 ) {
                    String listid = request.getParameter("listid");
                    if( listid != null && !listid.isEmpty() && listid.compareToIgnoreCase("undefined") != 0  ) {
                        json.put("error", "false");
                        json = GetListForStorylist( json, listid );
                    } else {
                        json.put("error","true");
                        json.put("reason", "list does not exist!");
                    }
                } else if ( page.compareToIgnoreCase("my_storylists") == 0 ) {
                    if ( user != null ) {
                        json.put("error", "false");
                        json = GetStorylistForUser( json, user.getUserID() );
                    } else {
                        json.put("error", "true");
                        json.put("reason", "User is not logged in!");
                    }
                } else if ( page.compareToIgnoreCase("storylists") == 0) {
                    String userid = request.getParameter("userid");
                    if ( userid != null && !userid.isEmpty() && userid.compareToIgnoreCase("undefined") != 0 ) {
                        json.put("error", "false");
                        json = GetStorylistForUser( json, userid );
                    } else {
                        json.put("error", "true");
                        json.put("reason", "user does not exist!");
                    }
			    } else if ( page.compareToIgnoreCase("rename_list") == 0 ) {
                    String listid = request.getParameter("listid");
                    String name = request.getParameter("name");
                    
                    if ( listid != null && !listid.isEmpty() && listid.compareToIgnoreCase("undefined") != 0 && 
                            name != null && !name.isEmpty() && name.compareToIgnoreCase("undefined") != 0 && user != null ) {                        
                        String owner = StoryManager.getInstance().getStorylistOwner(listid);
                        
                        if ( owner.equals( user.getUserID() ) ) {
                            if ( StoryManager.getInstance().renameStorylist( listid, name ) ) {
                                json.put("error", "false");
                            } else {
                                json.put("error", "true");
                                json.put("reason", "Cannot rename storylist");                                
                            }
                        } else {
                            json.put("error", "true");
                            json.put("reason", "user does not own this storylist!");
                        }
                    } else {
                        json.put("error", "true");
                        json.put("reason", "user does not exist!");
                    }
                } else if ( page.compareToIgnoreCase("delete_list") == 0 ) {
                    String listid = request.getParameter("listid");
                    
                    if ( listid != null && !listid.isEmpty() && listid.compareToIgnoreCase("undefined") != 0 && user != null ) {                        
                        String owner = StoryManager.getInstance().getStorylistOwner(listid);
                        
                        if ( owner.equals( user.getUserID() ) ) {
                            if ( StoryManager.getInstance().deleteStorylist( listid ) ) {
                                json.put("error", "false");
                            } else {
                                json.put("error", "true");
                                json.put("reason", "Cannot delete storylist");                                
                            }
                        } else {
                            json.put("error", "true");
                            json.put("reason", "user does not own this storylist!");
                        }
                    } else {
                        json.put("error", "true");
                        json.put("reason", "user does not exist!");
                    }
                }  else if ( page.compareToIgnoreCase("get_add_lists") == 0 ) {
                    if ( user != null ) {
                        String storyid = request.getParameter("storyid");
                        
                        if (storyid != null && !storyid.isEmpty() && storyid.compareToIgnoreCase("undefined") != 0  ) {
                            json.put("error", "false");
                            json = GetListsToAddStoryTo( json, user.getUserID(), storyid );
                        } else {
                            json.put("error", "true");
                            json.put("reason", "story is not specified");
                        }
                    } else {
                        json.put("error", "true");
                        json.put("reason", "User is not logged in!");
                    }
                }   else if ( page.compareToIgnoreCase("add_to_lists") == 0 ) {
                    if ( user != null ) {
                        String storyid = request.getParameter("storyid");
                        String listids = request.getParameter("listid");
                        
                        if (storyid != null && !storyid.isEmpty() && storyid.compareToIgnoreCase("undefined") != 0  &&
                                listids != null && !listids.isEmpty() && listids.compareToIgnoreCase("undefined") != 0) {
                            String[] lists = listids.split(",");
                            json.put("error", "false");
                            json = AddStoryToStorylists( json, user.getUserID(), storyid, lists );
                        } else {
                            json.put("error", "true");
                            json.put("reason", "Story and storylists must be specified!");
                        }
                    } else {
                        json.put("error", "true");
                        json.put("reason", "User is not logged in!");
                    }
                } else if ( page.compareToIgnoreCase("story_view_tags") == 0 ) {
                    String storyid = request.getParameter("storyid");
                    
                    if ( storyid != null && !storyid.isEmpty() && storyid.compareToIgnoreCase("undefined") != 0 && user != null ) {
                        json = getUserTags(json, user.getUserID(), Integer.parseInt(storyid));
                        json.put("error", "false");
                    } else {
                        json.put("error", "true");
                        json.put("reason", "user or story does not exist!");
                    }
                } else if (page.compareToIgnoreCase("my_storylist_delete") == 0) {
                    String storyid = request.getParameter("storyid");
                    String listid = request.getParameter("listid");
                    
                    if ( storyid != null && !storyid.isEmpty() && storyid.compareToIgnoreCase("undefined") != 0 && 
                            listid != null && !listid.isEmpty() && listid.compareToIgnoreCase("undefined") != 0 ) {
                        if (user != null && UserManager.getInstance().checkIfUserHasList(user.getUserID(), listid)) {
                            StoryManager.getInstance().removeStoryFromStorylist(storyid, listid);
                            json.put("error", "false");
                        } else {
                            json.put("error", "true");
                            json.put("reason", "invalid user!");                            
                        }
                    } else {
                        json.put("error", "true");
                        json.put("reason", "list or story does not exist!");
                    }
                } else if (page.compareToIgnoreCase("story_subs") == 0) {
                    if (user != null) {
                        json.put("error", "false");
                        json = getSubscribedStories(json, user.getUserID());
                    } else {
                        json.put("error", "true");
                        json.put("reason", "user is not logged in!");
                    }
                } else if (page.compareToIgnoreCase("user_subs") == 0) {
                    if (user != null) {
                        json.put("error", "false");
                        json = getSubscribedUsers(json, user.getUserID());
                    } else {
                        json.put("error", "true");
                        json.put("reason", "user is not logged in!");
                    }
                } else if (page.compareToIgnoreCase("unsubscribe_user") == 0) {
                    if (user != null) {
                        String userid = request.getParameter("userid");
                        
                        if (userid != null && !userid.isEmpty() && UserManager.getInstance().unsubscribeFromUser(user.getUserID(), userid)) {
                            json.put("error", "false");
                        } else {
                            json.put("error", "true");
                            json.put("reason", "Could not unsubscribe from user");                            
                        }
                    } else {
                        json.put("error", "true");
                        json.put("reason", "user is not logged in!");
                    }
                } else if (page.compareToIgnoreCase("unsubscribe_story") == 0) {
                    if (user != null) {
                        String storyid = request.getParameter("storyid");

                        if (storyid != null && !storyid.isEmpty() && UserManager.getInstance().unsubscribeFromStory(user.getUserID(), storyid)) {
                            json.put("error", "false");
                        } else {
                            json.put("error", "true");
                            json.put("reason", "Could not unsubscribe from story");                            
                        }
                    } else {
                        json.put("error", "true");
                        json.put("reason", "user is not logged in!");
                    }
                } else if (page.compareToIgnoreCase("all_tags") == 0) {
                    String[] alltags = TagConstant.getAllTagNames();
                    JSONArray array = new JSONArray();
                    for (String tag : alltags) {
                        array.put( tag );
                    }
                    
                    json.put("tags", array);
                    json.put("error", "false");
                } else if (page.compareToIgnoreCase("get_prompt") == 0) {
                    String promptid = request.getParameter("promptid");
                    if (promptid != null && !promptid.isEmpty()) {
                        json = GetPromptAsJSON(json, promptid);
                        json.put("error", "false");
                    } else {
                        json.put("error", "true");
                        json.put("reason","Invalid prompt id");                        
                    }
                } else if (page.compareToIgnoreCase("check_list_owner") == 0) {
                    String listid = request.getParameter("listid");
                    if (user != null && listid != null && !listid.isEmpty()) {
                        json.put("error", "false");
                        json.put("listid", listid);
                        
                        if (UserManager.getInstance().checkIfUserHasList(user.getUserID(), listid)) {
                            json.put("owner", "true");
                        } else {
                            json.put("owner", "false");
                        }
                    } else {
                        json.put("error", "true");
                        json.put("reason", "user or list is null");
                    }
                } else if (page.compareToIgnoreCase("user_check") == 0) {
                    String userid = request.getParameter("userid");
                    if (userid != null && !userid.isEmpty()) {
                        json.put("exists", UserManager.getInstance().getUser(userid) != null);
                        json.put("error", "false");
                    } else {
                        json.put("error", "true");
                        json.put("reason", "user is null");                        
                    }
			    } else {
                    json.put("error", "true");
                    json.put("reason","Could not update the requested page");
                }
			
			} else {
				json.put("error", "true");
				json.put("reason","Could not update the requested page");
			}
		} catch ( JSONException e ) {
			
		}
		response.getWriter().print( json.toString() );
	}
	
	protected JSONObject GetUserInfo(JSONObject json, User user) {
		try {
			if( user != null ) {
				json.put("userid", user.getUserID() );
				json.put("error", "false");
				json.put("fname", user.getFirstName() );
				json.put("lname", user.getLastName() );
				json.put("gender", user.getGender() );
				json.put("location", user.getLocation() );
				json.put("lastupdate", user.getLastUpdate() );
				json.put("datecreate", user.getDateCreated() );
				json.put("biography", user.getBiography() );
				JSONArray storyArray = new JSONArray();
				for( Story story : UserManager.getInstance().getUserContributedStories( user.getUserID() )) {
					JSONObject storyJSON = new JSONObject();
					storyJSON.put("storyid", story.getStoryID() );
					storyJSON.put("storytitle", story.getTitle() );
					storyArray.put( storyJSON );
				}
				json.put("stories", storyArray );
			} else {
				json.put("error", "true");
			}
		} catch ( JSONException e ) {
			
		}
		return json;
	}

	protected JSONObject GetPromptAsJSON(JSONObject json, String promptid) {
        Prompt prompt = new Prompt(Integer.parseInt(promptid));
        
        try {
            json.put("promptid", prompt.getID());
            json.put("textprompt", prompt.getTextPrompt());
            json.put("imagefilepath", prompt.getImageFilePath());
        } catch (JSONException e) {}
        
        return json;
    }

    protected JSONObject getSubscribedUsers(JSONObject json, String userID) {
        ArrayList<DatabaseObjects> users = UserManager.getInstance().getSubscribedUsers(userID);
        JSONArray arrayOfUsers = new JSONArray();
        try {
            for( DatabaseObjects user : users ) {
                User aUser = (User) user;
                JSONObject jsonUser = new JSONObject();
                jsonUser.put("userid", aUser.getUserID() );
                jsonUser.put("datecreated", aUser.getDateCreated() );
                jsonUser.put("lastupdated", aUser.getLastUpdate() );
                
                arrayOfUsers.put( jsonUser );
            }
            json.put( "users" , arrayOfUsers );
        } catch ( JSONException e ) {}
        
        return json;
    }

    protected JSONObject getSubscribedStories(JSONObject json, String userID) {
        ArrayList<DatabaseObjects> stories = UserManager.getInstance().getSubscribedStories(userID);
        JSONArray arrayOfStories = new JSONArray();
        try {
            for( DatabaseObjects story : stories ) {
                Story aStory = (Story) story;
                JSONObject jsonStory = new JSONObject();
                jsonStory.put("storyid", aStory.getStoryID() );
                jsonStory.put("storytitle", aStory.getTitle() );
                jsonStory.put("authorid", aStory.getAuthorID() );
                
                jsonStory.put("createdate", aStory.getCreatedTimestamp());
                
                ArrayList<Post> posts = aStory.getAllPosts();
                jsonStory.put("numpost" , posts.size() );
                String preview = posts.get( posts.size() - 1 ).getPost();
                if (preview.length() > 240) {
                    preview = preview.substring( 0, 240) + " ... ";
                }
                jsonStory.put("preview", preview);
                jsonStory.put("timestamp", posts.get( posts.size() - 1 ).getTimeStamp() );

                jsonStory.put("lastposterid", posts.get( posts.size() - 1).getUserID());
                arrayOfStories.put( jsonStory );
            }
            json.put( "stories" , arrayOfStories );
        } catch ( JSONException e ) {}
        
        return json;
    }

    protected JSONObject AddStoryToStorylists(JSONObject json, String userID,
            String storyid, String[] lists) {
	    
	    for (String list : lists) {
	        if (UserManager.getInstance().checkIfUserHasList(userID, list)) {
	            StoryManager.getInstance().addStoryToStorylist(list, storyid);
	        }	        
	    }
        
        return json;
    }

    protected JSONObject GetListsToAddStoryTo(JSONObject json, String userid, String storyid) {
	    
        ArrayList<Storylist> lists = StoryManager.getInstance().getListsToAddStoryTo( userid , storyid );
        JSONArray arrayOfStorylists = new JSONArray();
        try {
            for( Storylist list : lists ) {
                Storylist aList = (Storylist) list;
                JSONObject jsonList = new JSONObject();
                jsonList.put("listid", aList.getListID() );
                jsonList.put("userid", aList.getUserID() );
                jsonList.put("name", aList.getName() );
                jsonList.put("count", aList.getCount());
                arrayOfStorylists.put( jsonList );
            }
            
            json.put( "storylists" , arrayOfStorylists );
        } catch ( JSONException e ) {}
        
        return json;
    }

    protected JSONObject getUserTags(JSONObject json, String userId, int storyId) {
	    ArrayList<String> tags = TagManager.getInstance().getUserTags(userId, storyId);
	    JSONArray arrayOfTags = new JSONArray();
	    
	    try {
	        for ( String tag : tags ) {
	            arrayOfTags.put( tag );
	        }
	        
	        json.put( "tags", arrayOfTags );
	    } catch ( JSONException e ) {}
	    
	    return json;
    }

    protected JSONObject GetStorylistForUser(JSONObject json, String userID) {
        ArrayList<Storylist> lists = StoryManager.getInstance().getStorylistsOfUser( userID );
        JSONArray arrayOfStorylists = new JSONArray();
        try {
            for( Storylist list : lists ) {
                Storylist aList = (Storylist) list;
                JSONObject jsonList = new JSONObject();
                jsonList.put("listid", aList.getListID() );
                jsonList.put("userid", aList.getUserID() );
                jsonList.put("name", aList.getName() );
                jsonList.put("count", aList.getCount());
                arrayOfStorylists.put( jsonList );
            }
            
            json.put( "storylists" , arrayOfStorylists );
        } catch ( JSONException e ) {}
        
        return json;
    }

    protected JSONObject GetListForStorylist(JSONObject json, String listid) {
        ArrayList<Story> list = StoryManager.getInstance().getStoriesInList( listid );
        JSONArray arrayOfStories = new JSONArray();
        try {
            for( Story story : list ) {
                Story aStory = (Story) story;
                JSONObject jsonStory = new JSONObject();
                jsonStory.put("storyid", aStory.getStoryID() );
                jsonStory.put("storytitle", aStory.getTitle() );
                jsonStory.put("authorid", aStory.getAuthorID() );
                jsonStory.put("createdate", aStory.getCreatedTimestamp());
                
                ArrayList<Post> posts = aStory.getAllPosts();
                jsonStory.put("numpost" , posts.size() );
                
                String preview = posts.get( posts.size() - 1 ).getPost();
                if (preview.length() > 240) {
                    preview = preview.substring( 0, 240) + " ... ";
                }
                jsonStory.put("preview", preview);
                jsonStory.put("timestamp", posts.get( posts.size() - 1 ).getTimeStamp() );
                jsonStory.put("lastposterid", posts.get( posts.size() - 1).getUserID());
                arrayOfStories.put( jsonStory );
            }
            json.put( "stories" , arrayOfStories );
            json.put( "title" , StoryManager.getInstance().getStorylistNameFromId(listid));
            json.put( "userid" , StoryManager.getInstance().getStorylistOwner(listid));
        } catch ( JSONException e ) {}
        
        return json;
    }

    protected JSONObject GetStoryInfoForStory(JSONObject json, String storyid, User user) {
		Story story = StoryManager.getInstance().getStoryByID( Integer.parseInt(storyid) );
		if( story != null ) {
			HashMap<String,Integer> tags = story.getAllTags();
			ArrayList<Post> posts = story.getAllPosts();
			
			JSONArray tagArray = new JSONArray();
			JSONArray postArray = new JSONArray();
			try {
				for( Entry<String, Integer> tagEntry : tags.entrySet() ) {
					JSONObject jsonTag = new JSONObject();
					jsonTag.put("tagname", tagEntry.getKey());
					jsonTag.put("count", tagEntry.getValue() );
					tagArray.put( jsonTag );
				}
				for( Post aPost : posts ) {
					JSONObject jsonPost = new JSONObject();
					jsonPost.put("postid", aPost.getPostID() );
					jsonPost.put("post", aPost.getPost() );
					jsonPost.put("userid", aPost.getUserID() );
					if( user == null || !user.isSubscribedToWriter( aPost.getUserID() ) ) {
						jsonPost.put("subscribed", "false");
					} else { 
						jsonPost.put("subscribed", "true");
					}
					jsonPost.put("timestamp", aPost.getTimeStamp() );
					postArray.put( jsonPost );
				}
				json.put("tags", tagArray );
				json.put("posts", postArray );
				if( user != null && user.isSubscribedToStory( story.getStoryID() ) ) {
					json.put("storysub", "true");
				} else {
					json.put("storysub", "false");
				}
				if( user != null && story.userVoted( user.getUserID() ) ) {
					json.put("upvoted", "true" );
				} else {
					json.put("upvoted", "false");
				}
			} catch (JSONException e ) {
				
			}
		}
		return json;
	}

	protected JSONObject GetPromptListAsJSON(JSONObject json) {
		ArrayList<Prompt> prompts = StoryManager.getInstance().getAllPrompt();
		JSONArray arrayOfPrompts = new JSONArray();
		try {
			for( Prompt prompt : prompts ) {
				JSONObject jsonPrompt = new JSONObject();
				jsonPrompt.put("promptid", prompt.getID() );
				jsonPrompt.put("userid", prompt.getUserID() );
				jsonPrompt.put("text", prompt.getTextPrompt() );
				jsonPrompt.put("imgpath", prompt.getImageFilePath() );
				jsonPrompt.put("timestamp", prompt.getTimestamp() );
				arrayOfPrompts.put( jsonPrompt );
			}
			json.put("prompts", arrayOfPrompts );
		} catch (JSONException e ) { 
		
		}
		return json;
	}
	
	protected JSONObject GetStorySearchResultsAsJSON(JSONObject json, String keyword, String creator, 
	        int tagIndex, String[] tagsSelected, String sort){
		ArrayList<DatabaseObjects> storiesResults;

		storiesResults = StoryManager.getInstance().advancedSearch(keyword, creator, tagsSelected, sort);
		JSONArray stories = new JSONArray();
		try {
			for( DatabaseObjects story : storiesResults ) {
				Story aStory = (Story) story;
				JSONObject jsonStory = new JSONObject();
				jsonStory.put("storyid", aStory.getStoryID() );
				jsonStory.put("storytitle", aStory.getTitle() );
				jsonStory.put("authorid", aStory.getAuthorID() );
				jsonStory.put("viewcount", aStory.getViewCount() );
				jsonStory.put("votecount", aStory.getVoteCount() );
				
				jsonStory.put("createdate", aStory.getCreatedTimestamp());
				jsonStory.put("createdateNum", aStory.getCreatedTimestampNum());
				
				ArrayList<Post> posts = aStory.getAllPosts();
				jsonStory.put("numpost" , posts.size() );
				if (posts.size() > 0) {
				    String preview = posts.get( posts.size() - 1 ).getPost(); 
				
    				if (preview.length() > 240) {
    				    preview = preview.substring( 0, 240) + " ... ";
    				}
    				jsonStory.put("preview", preview);

                    jsonStory.put("timestamp", posts.get( posts.size() - 1 ).getTimeStamp() );
                    jsonStory.put("timestampNum", posts.get( posts.size() - 1 ).getTimeStampinNum());
				}
				
				ArrayList<Comment> comments = aStory.getAllComments();
				if (comments.size() > 0)
				    jsonStory.put("lastCommentTimestampNum", comments.get( comments.size() - 1 ).getTimeStampinNum());
				else
				    jsonStory.put("lastCommentTimestampNum", new Date().toString());
				
				jsonStory.put("lastposterid", posts.get( posts.size() - 1 ).getUserID());
				stories.put( jsonStory );
			}
			json.put( "stories" , stories );
		} catch ( JSONException e ) {
			
		}
		return json;
	}
	
	protected JSONObject GetStoryListAsJSON(JSONObject json) {
		ArrayList<DatabaseObjects> stories = StoryManager.getInstance().getAll();
		JSONArray arrayOfStories = new JSONArray();
		try {
			for( DatabaseObjects story : stories ) {
				Story aStory = (Story) story;
				JSONObject jsonStory = new JSONObject();
				jsonStory.put("storyid", aStory.getStoryID() );
				jsonStory.put("storytitle", aStory.getTitle() );
				jsonStory.put("authorid", aStory.getAuthorID() );
				jsonStory.put("viewcount", aStory.getViewCount() );
				jsonStory.put("votecount", aStory.getVoteCount() );
				
				jsonStory.put("createdate", aStory.getCreatedTimestamp());
				jsonStory.put("createdateNum", aStory.getCreatedTimestampNum());
				
				ArrayList<Post> posts = aStory.getAllPosts();
				jsonStory.put("numpost" , posts.size() );
				String preview = posts.get( posts.size() - 1 ).getPost();
				if (preview.length() > 240) {
				    preview = preview.substring( 0, 240) + " ... ";
				}
				jsonStory.put("preview", preview);
				jsonStory.put("timestamp", posts.get( posts.size() - 1 ).getTimeStamp() );
				jsonStory.put("timestampNum", posts.get( posts.size() - 1 ).getTimeStampinNum());
				
				ArrayList<Comment> comments = aStory.getAllComments();
				if( comments.size() > 0 ) {
					jsonStory.put("lastCommentTimestampNum", comments.get( comments.size() - 1 ).getTimeStampinNum());
				}
				String tagList = "";
				for( String tag : aStory.getAllTags().keySet() ) {
					if( aStory.getAllTags().get( tag ) > 0 ) {
						tagList = tagList.concat(tag);
					}
				}
				
				jsonStory.put("tags", tagList );
				jsonStory.put("lastposterid", posts.get( posts.size() - 1).getUserID());
				arrayOfStories.put( jsonStory );
			}
			json.put( "stories" , arrayOfStories );
		} catch ( JSONException e ) {
			
		}
		return json;
	}
	
	protected JSONObject GetTopViewedListAsJSON(JSONObject json) {
		int topN = 10; //specifies how many top stories that are displayed
		ArrayList<Story> allViewedStories = StoryManager.getInstance().getTopViewedStories(topN);
		JSONArray arrayOfStories = new JSONArray();
		try {
			for( Story story : allViewedStories ) {
				JSONObject jsonStory = new JSONObject();
				jsonStory.put("storyid", story.getStoryID() );
				jsonStory.put("storytitle", story.getTitle() );
				jsonStory.put("authorid", story.getAuthorID() );
				jsonStory.put("viewcount", story.getViewCount() );
				jsonStory.put("votecount", story.getVoteCount() );
				
				jsonStory.put("createdate", story.getCreatedTimestamp());
				jsonStory.put("createdateNum", story.getCreatedTimestampNum());
				
				ArrayList<Post> posts = story.getAllPosts();
				jsonStory.put("numpost" , posts.size() );
				String preview = posts.get( posts.size() - 1 ).getPost();
				if (preview.length() > 240) {
					preview = preview.substring( 0, 240) + " ... ";
				}
				jsonStory.put("preview", preview);
				jsonStory.put("timestamp", posts.get( posts.size() - 1 ).getTimeStamp() );
				jsonStory.put("timestampNum", posts.get( posts.size() - 1 ).getTimeStampinNum());
				
				ArrayList<Comment> comments = story.getAllComments();
				if( comments.size() > 0 ) {
					jsonStory.put("lastCommentTimestampNum", comments.get( comments.size() - 1 ).getTimeStampinNum());
				}
				String tagList = "";
				for( String tag : story.getAllTags().keySet() ) {
					if( story.getAllTags().get( tag ) > 0 ) {
						tagList = tagList.concat(tag);
					}
				}
				
				jsonStory.put("tags", tagList );
				jsonStory.put("lastposterid", posts.get( posts.size() - 1).getUserID());
				arrayOfStories.put( jsonStory );
			}
			json.put( "stories" , arrayOfStories );
		} catch ( JSONException e ) {
			
		}
		return json;
	}
	
	protected JSONObject GetTopVotedListAsJSON(JSONObject json) {
		int topN = 10; //specifies how many top stories that are displayed
		ArrayList<Story> allVotedStories = StoryManager.getInstance().getTopVotedStories(topN);
		JSONArray arrayOfStories = new JSONArray();
		try {
			for( Story story : allVotedStories ) {
				JSONObject jsonStory = new JSONObject();
				jsonStory.put("storyid", story.getStoryID() );
				jsonStory.put("storytitle", story.getTitle() );
				jsonStory.put("authorid", story.getAuthorID() );
				jsonStory.put("viewcount", story.getViewCount() );
				jsonStory.put("votecount", story.getVoteCount() );
				
				jsonStory.put("createdate", story.getCreatedTimestamp());
				jsonStory.put("createdateNum", story.getCreatedTimestampNum());
				
				ArrayList<Post> posts = story.getAllPosts();
				jsonStory.put("numpost" , posts.size() );
				String preview = posts.get( posts.size() - 1 ).getPost();
				if (preview.length() > 240) {
					preview = preview.substring( 0, 240) + " ... ";
				}
				jsonStory.put("preview", preview);
				jsonStory.put("timestamp", posts.get( posts.size() - 1 ).getTimeStamp() );
				jsonStory.put("timestampNum", posts.get( posts.size() - 1 ).getTimeStampinNum());
				
				ArrayList<Comment> comments = story.getAllComments();
				if( comments.size() > 0 ) {
					jsonStory.put("lastCommentTimestampNum", comments.get( comments.size() - 1 ).getTimeStampinNum());
				}
				String tagList = "";
				for( String tag : story.getAllTags().keySet() ) {
					if( story.getAllTags().get( tag ) > 0 ) {
						tagList = tagList.concat(tag);
					}
				}
				
				jsonStory.put("tags", tagList );
				jsonStory.put("lastposterid", posts.get( posts.size() - 1).getUserID());
				arrayOfStories.put( jsonStory );
			}
			json.put( "stories" , arrayOfStories );
		} catch ( JSONException e ) {
			
		}
		return json;
	}

	protected JSONObject GetSubscriptionUpdatesAsJSON( JSONObject json , String userID) {
		ArrayList<String[]> updates;
		if( userID == null ) {
			updates = StoryManager.getInstance().getMostRecentStoryUpdates();
		} else {
			User user = UserManager.getInstance().getUser( userID ); 
			updates = user.getSubscriptionUpdates();
		}
		
		JSONArray arrayOfUpdates = new JSONArray();
		String[] columnHeaders;
		if( updates != null && updates.size() > 0 ) {
			columnHeaders = updates.get( 0 );
			try {
				for( int i = 1; i < updates.size(); i++ ) {
					String[] row = updates.get( i );
					JSONObject jsonRow = new JSONObject();
					for( int j = 0; j < row.length; j++ ) { 
						jsonRow.put( columnHeaders[j], row[j] );
					}
					arrayOfUpdates.put( jsonRow );
				}
				json.put("newsfeed", arrayOfUpdates );
			} catch ( JSONException e ) {
				
			}
		} else {
			try {
				json.put("newsfeed","No Newsfeed data available at the moment! Please try again later");
			} catch (JSONException e) {

			}
		}
		return json;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
